package concurrencyPractice.chapter04;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序4-7 将线程安全委托给 ConcurrentHashMap
 * map 不可变
 * @date 2023/12/28 16:32:24
 */
public class DelegatingVehicleTracker {
    private final ConcurrentHashMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(Map<String, Point> points) {
        locations = new ConcurrentHashMap<>(points);
        unmodifiableMap = Collections.unmodifiableMap(locations);
    }

    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }
    public Point getLocation(String id) {
        return locations.get(id);
    }
    public void setLocation(String id, int x, int y) {
        if(locations.replace(id, new Point(x, y)) == null) {
            throw new IllegalArgumentException("invalid vehicle name" + id);
        }
    }
}
